package com.hoas.keystore.decoder;

import com.hoas.keystore.factory.aes.AESDecoderFactory;
import com.hoas.keystore.factory.rsa.RSADecoderFactory;
import com.hoas.keystore.po.MerchantKey;


/**
 * @Author: Administrator
 * @Date: 2018/11/6 18:04
 */
public class DecoderFactory {

    public static final int DECODER_TYPE_CLIENT = 1;
    public static final int DECODER_TYPE_SERVER = 2;

    public static final String ENCRYPT_TYPE_RSA = "RSA";
    public static final String ENCRYPT_TYPE_AES = "AES";
    public static final String ENCRYPT_TYPE_NONE = "NONE";

    private MerchantKey merchantKey;

    public DecoderFactory(MerchantKey merchantKey) {
        this.merchantKey = merchantKey;
    }

    public IDecoder getServerDecoder() {

        return getDecoder( DECODER_TYPE_SERVER);
    }

    public IDecoder getClientDecoder() {

        return getDecoder( DECODER_TYPE_CLIENT);

    }

    public IDecoder getDecoder(int decoderType) {


        if (ENCRYPT_TYPE_RSA.equalsIgnoreCase(merchantKey.getKeyVersion())) {

            if (decoderType == DECODER_TYPE_CLIENT) {
                return RSADecoderFactory.getClientDecoder( merchantKey );
            } else {
                return RSADecoderFactory.getServerDecoder( merchantKey );
            }

        } else if(ENCRYPT_TYPE_AES.equalsIgnoreCase(merchantKey.getKeyType())) {

            return AESDecoderFactory.getDecoder( merchantKey );

        } else if(ENCRYPT_TYPE_NONE.equalsIgnoreCase(merchantKey.getKeyType())) {

            return new NoneDecoder();

        }

        return null;
    }

    public MerchantKey genKeyPairs() {

        MerchantKey newkey = new MerchantKey();
        newkey.setKeyType( merchantKey.getKeyType() );
        newkey.setMerchantId( merchantKey.getMerchantId() );
        newkey.setKeyVersion( "" + System.currentTimeMillis() );

        if (ENCRYPT_TYPE_RSA.equalsIgnoreCase(merchantKey.getKeyType())) {

            RSADecoderFactory.genKeyPairs( newkey );

        } else if(ENCRYPT_TYPE_AES.equalsIgnoreCase(merchantKey.getKeyType())) {

            AESDecoderFactory.genKeyPairs( newkey);

        }

        return newkey;

    }

}
